// 获取所有书签
async function getAllBookmarks() {
  return new Promise(resolve => {
    chrome.bookmarks.getTree(tree => resolve(tree));
  });
}

// 序列化书签数据
function serializeBookmarks(bookmarks) {
  return JSON.stringify({
    bookmarks: flattenBookmarks(bookmarks)
  });
}

// 扁平化书签树结构
function flattenBookmarks(nodes, result = []) {
  nodes.forEach(node => {
    if (node.url) {
      result.push({
        title: node.title,
        url: node.url,
        dateAdded: node.dateAdded
      });
    }
    if (node.children) {
      flattenBookmarks(node.children, result);
    }
  });
  return result;
}

// 发送API请求
async function sendBookmarksToAPI(bookmarksData, searchQuery, token) {
    try {
      const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          model: "deepseek-ai/DeepSeek-V3",
          messages: [{
            role: "user",
            content: `请根据用户的搜索词 "${searchQuery}"，从以下书签列表中推荐相关的书签，并简要说明理由。书签数据：${JSON.stringify(bookmarksData)}`
          }],
          temperature: 0.7
        })
      });
  
      if (!response.ok) {
        const errorText = await response.text(); // 获取详细错误信息
        throw new Error(`API请求失败: ${response.status} - ${errorText}`);
      }
      const data = await response.json();
      return data.choices[0].message.content;
    } catch (error) {
      console.error('API请求错误:', error);
      throw error;
    }
  }

// 安全存储token
// 获取硬编码token
async function getAPIToken() {
  return 'sk-nrvjihoykgbjabnelziszukgkcankraqcwtvohvpcuepuyyz';
}

export { getAllBookmarks, serializeBookmarks, sendBookmarksToAPI, getAPIToken };
const tokenInput = document.getElementById('apiToken');
const saveTokenBtn = document.getElementById('saveToken');
const resultList = document.getElementById('results');
const searchBtn = document.getElementById('searchBtn');

if (!tokenInput || !saveTokenBtn || !resultList || !searchBtn) {
  console.error('关键DOM元素未找到，请检查HTML结构');
  return;
}
if (saveTokenBtn) {
  saveTokenBtn.addEventListener('click', () => {
    chrome.storage.local.set({ apiToken: tokenInput.value });
    alert('Token已保存');
  });
}

if (searchBtn) {
  searchBtn.addEventListener('click', getRecommendations);
}